package com.soul.gateway.filters;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mdoya
 * @version 1.0
 * @description: 网关过滤器：鉴权、负载均衡、限流
 */
@Slf4j
@Component
public class GatewayFilter implements GlobalFilter, Ordered {

    @Value("${gateway.excludedUrls}")
    private List<String> gatewayExcludedUrls;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 鉴权逻辑
     * @param exchange 交换机: 获取request, response
     * @param chain 过滤链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uriPath = request.getURI().getPath();
        if (gatewayExcludedUrls.contains(uriPath)) {
            return chain.filter(exchange);
        }
        String authorization = request.getHeaders().getFirst("Authorization");
        if (StringUtils.isNotEmpty(authorization)){
            String newToken = authorization.replace("Bearer ", "");
            String redisToken = stringRedisTemplate.opsForValue().get("TOKEN_" + newToken);
            if (StringUtils.isNotEmpty(redisToken)){
                log.debug("***********用户已登录**********");
                return chain.filter(exchange);
            }
        }

        log.error("***********用户未登录**********");
        //8. 没值 401， 用户没有登录
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("errCode", HttpStatus.UNAUTHORIZED);
        responseData.put("errMessage", "用户未登录");
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(responseData));
        return response.writeWith(Mono.just(dataBuffer));
    }


    /**
     * 返回过滤链中执行的顺序
     * 值越小越优先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
